// 引入配置信息或者自己创建个 config 对象
import config from "../config.js";
// let config = {
// 	// 上传图片的API
// 	upload_img_url:'http://www.test.com/index.php/index/upload'
// }
class Uploader {

	choose(num) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: num,
				success(res) {
					// console.log(res);
					// 缓存文件路径
					resolve(res.tempFilePaths)
				},
				fail(err) {
					console.log(err)
					reject(err)
				}
			})
		})
	}

	upload_one(path,type) {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '上传中'
			})
			let token = uni.getStorageSync("token") || '';
			uni.uploadFile({
				url: config.upload_img_url, //仅为示例，非真实的接口地址
				filePath: path,
				name: 'image',
				formData: {
					width: '200',
					height: '200',
					'token': token,
					dir: type
				},
				success: (uploadFileRes) => {
					if ("string" === typeof uploadFileRes.data) {
						resolve(JSON.parse(uploadFileRes.data).data)
					} else {
						resolve(uploadFileRes.data.data)
					}
				},
				fail:(res)=>{
					console.log(res);
				},
				complete() {
					uni.hideLoading()
				}
			});
		})
	}

	upload(path_arr,type) {
		let num = path_arr.length;
		return new Promise(async (resolve, reject) => {
			let img_urls = []
			for (let i = 0; i < num; i++) {
				let img_url = await this.upload_one(path_arr[i],type);
				console.log(img_url)
				img_urls.push(img_url)
			};
			resolve(img_urls)
		})
	}

	choose_and_upload(num,type) {
		return new Promise(async (resolve, reject) => {
			let path_arr = await this.choose(num);
			let img_urls = await this.upload(path_arr,type);
			resolve(img_urls);
		})
	}
}
export default Uploader;
